<template>
    <div v-loading="pager.loading" class="flex flex-col h-full">
        <el-scrollbar>
            <div class="grid gap-4 4xl:grid-cols-6 3xl:grid-cols-5 2xl:grid-cols-4 xl:grid-cols-3 sm:grid-cols-2">
                <div
                    v-for="(item, index) in (pager.lists as SquareMusicResponse[])"
                    :id="`music-item-${item.id}`"
                    :key="index"
                    class="music-item"
                    @click="selectMusic(item)"
                >
                    <div class="w-[100px] h-[100px] relative">
                        <photos
                            width="100%"
                            height="100%"
                            radius="12px"
                            :src="item.cover_url"
                        />

                        <div
                            v-if="currentId == item.id && playing"
                            class="absolute inset-0 flex items-center justify-center text-white"
                        >
                            <icon name="el-icon-VideoPause" :size="20" />
                        </div>

                        <div
                            v-if="currentId == item.id && !playing"
                            class="absolute inset-0 flex items-center justify-center text-white"
                        >
                            <icon name="el-icon-VideoPlay" :size="26" />
                        </div>
                    </div>

                    <div class="flex-1 flex flex-col justify-between h-full ml-4 py-1">
                        <div
                            class="text-lg font-bold line-clamp-1"
                            :class="{
                                '!text-primary': currentId === item.id
                            }"
                        >
                            {{ item.title }}
                        </div>

                        <div class="text-tx-secondary line-clamp-1">
                            {{ item.tags }}
                        </div>

                        <div class="flex justify-between">
                            <div v-if="configs.is_user" class="flex items-center">
                                <ElAvatar :size="26" :src="item?.user?.avatar" />
                                <span class="ml-1.5 text-xs text-tx-placeholder">
                                    {{ item.user?.nickname }}
                                </span>
                            </div>

                            <div class="flex items-center mt-[4px] text-tx-secondary">
                                {{ datetimeUtil.secondToMin(item.duration) }}
                            </div>

                            <div class="flex items-center gap-2.5">
                                <el-tooltip
                                    effect="dark"
                                    content="喜欢"
                                    placement="bottom"
                                >
                                    <div>
                                        <icon
                                            v-if="!item.is_collect"
                                            class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                            name="el-icon-Star"
                                            size="20"
                                            color="#556477"
                                            @click.stop="handleCollect(item.code, item.is_collect)"
                                        />
                                        <icon
                                            v-else
                                            class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                            name="el-icon-StarFilled"
                                            size="20"
                                            color="#fd5656"
                                            @click.stop="handleCollect(item.code, item.is_collect)"
                                        />
                                    </div>
                                </el-tooltip>
                                <el-tooltip
                                    v-if="item.lyric"
                                    effect="dark"
                                    content="歌词"
                                    placement="bottom"
                                >
                                    <div>
                                        <icon
                                            class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                            name="el-icon-Tickets"
                                            size="18"
                                            color="#556477"
                                            @click.stop="openTips(item.lyric, '歌词')"
                                        />
                                    </div>
                                </el-tooltip>
                                <el-tooltip
                                    effect="dark"
                                    content="下载"
                                    placement="bottom"
                                >
                                    <div @click.stop="handleDownload(item.audio_url, item.title)">
                                        <icon
                                            class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                            name="el-icon-Download"
                                            size="24"
                                            color="#556477"
                                        />
                                    </div>
                                </el-tooltip>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="pager.lists.length <= 0 && !firstLoading">
                <el-empty description="空空如也~" />
            </div>
        </el-scrollbar>

        <div
            v-if="pager.lists.length > 0 && !firstLoading"
            class="flex justify-center my-4"
        >
            <paging
                v-model="pager"
                layout="prev, pager, next"
                @change="queryLists"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import { watchDebounced } from '@vueuse/core'
import { useMusicPlay } from '~/pages/apply/music/hooks/useMusicPlay'
import { popupEnum } from '~/enums/app'
import useAppStore from '~/stores/app'
import useUserStore from '~/stores/user'
import datetimeUtil from '~/utils/datetime'
import squareApi from '~/api/square'
import musicApi from '~/api/apply/music'
import downloadUtil from '~/utils/download'

const props = withDefaults(
    defineProps<{
        cateId?: number;
        keyword?: string;
        configs?: SquareSettingResponse;
    }>(),
    {
        cateId: 0,
        keyword: '',
        configs: {} as SquareSettingResponse | any
    }
)

const appStore = useAppStore()
const userStore = useUserStore()
const firstLoading = ref<boolean>(true)

const {
    playing,
    currentId,
    setMusic,
    togglePlay,
    setCurrentId
} = useMusicPlay()

// 查询参数
const queryParams = reactive({
    cate: props.cateId,
    keyword: props.keyword
})

// 分页查询
const { pager, queryLists, resetPaging } = usePaging({
    fetchFun: squareApi.music,
    params: queryParams
})

/**
 * 选择播放
 *
 * @param item
 * @author zero
 */
const selectMusic = (item: any) => {
    if (item.id === currentId.value) {
        togglePlay()
        return
    }
    setCurrentId(item.id)
}

/**
 * 收藏记录
 *
 * @param {string} code
 * @param {boolean} status
 * @author zero
 */
const handleCollect = async (code: string, status: boolean) => {
    if (!userStore.isLogin) {
        return appStore.setPopup(popupEnum.LOGIN)
    }

    await musicApi.collect(code)
    await queryLists()
    if (status) {
        feedback.msgSuccess('取消成功')
    } else {
        feedback.msgSuccess('收藏成功')
    }
}

/**
 * 下载音乐
 *
 * @param {string} url
 * @param {string} name
 * @author zero
 */
const handleDownload = async (url: string, name: string) => {
    try {
        if (!userStore.isLogin) {
            return appStore.setPopup(popupEnum.LOGIN)
        }

        const res = await $request.get(
            { url, responseType: 'blob', baseURL: '' },
            { isReturnDefaultResponse: true, apiPrefix: '' }
        )

        const blob = new Blob([res._data], {
            type: res.headers.get('Content-Type')
        })
        const link = window.URL.createObjectURL(blob)
        downloadUtil.file(link, name)
    } catch (error) {
        feedback.msgError('音乐下载失败: ' + error)
    }
}

/**
 * 打开提示窗
 *
 * @param {string} content
 * @param {string} title
 * @author zero
 */
const openTips = (content: string, title: string) => {
    feedback.confirm(content, title, {
        showCancelButton: false,
        type: '',
        customStyle: { 'max-width': '550px' }
    })
}

// 监听分类切换
watch(
    () => props.cateId,
    async () => {
        queryParams.cate = props.cateId
        queryParams.keyword = props.keyword
        await queryLists()
        setMusic(pager.lists)
        firstLoading.value = false
    },
    { immediate: true }
)

// 简体关键词搜索
watchDebounced(
    () => props.keyword,
    async (value) => {
        queryParams.keyword = value
        await resetPaging()
        setMusic(pager.lists)
    },
    {
        debounce: 500
    }
)
</script>

<style scoped lang="scss">
.music-item {
    position: relative;
    display: flex;
    align-items: center;
    width: 100%;
    padding: 18px;
    overflow: hidden;
    cursor: pointer;
    background: var(--el-bg-color);
    border-radius: 12px;
    &:hover {
        box-shadow: 0 6px 8px 0 rgb(28 31 35 / 12%);
    }
}
</style>
